/**
 * Copyright (c) 2016-2019 人人开源 All rights reserved.
 *
 * 
 *
 * 版权所有，侵权必究！
 */

package com.hx01.common.exception;

import com.baomidou.mybatisplus.extension.api.IErrorCode;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 自定义异常
 */
public class RRException extends RuntimeException {
	private static final long serialVersionUID = 1L;
	
    private String msg;
    private long code = 500;
    
    public RRException(String msg) {
		super(msg);
		this.msg = msg;
	}
	
	public RRException(String msg, Throwable e) {
		super(msg, e);
		this.msg = msg;
	}
	
	public RRException(String msg, long code) {
		super(msg);
		this.msg = msg;
		this.code = code;
	}
	
	public RRException(String msg, long code, Throwable e) {
		super(msg, e);
		this.msg = msg;
		this.code = code;
	}

	public RRException(IErrorCode errorCode, String errorMessage) {
		super(errorCode.toString() + " - " + errorMessage);
		this.code = errorCode.getCode();
	}

	private RRException(IErrorCode errorCode, String errorMessage, Throwable cause) {
		super(errorCode.toString() + " - " + getMessage(errorMessage) + " - " + getMessage(cause), cause);

		this.code = errorCode.getCode();
	}

	public static RRException asRRException(IErrorCode errorCode) {
		return new RRException(errorCode.getMsg(), errorCode.getCode());
	}

	public static RRException asRRException(IErrorCode errorCode, String message) {
		return new RRException(errorCode, message);
	}

	public static RRException asRRException(IErrorCode errorCode, String message, Throwable cause) {
		if (cause instanceof RRException) {
			return (RRException) cause;
		}
		return new RRException(errorCode, message, cause);
	}

	public static RRException asRRException(IErrorCode errorCode, Throwable cause) {
		if (cause instanceof RRException) {
			return (RRException) cause;
		}
		return new RRException(errorCode, getMessage(cause), cause);
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public long getCode() {
		return code;
	}

	public void setCode(int code) {
		this.code = code;
	}

	private static String getMessage(Object obj) {
		if (obj == null) {
			return "";
		}

		if (obj instanceof Throwable) {
			StringWriter str = new StringWriter();
			PrintWriter pw = new PrintWriter(str);
			((Throwable) obj).printStackTrace(pw);
			return str.toString();
			// return ((Throwable) obj).getMessage();
		} else {
			return obj.toString();
		}
	}
}
